/*
 * @lc app=leetcode.cn id=707 lang=swift
 *
 * [707] 设计链表
 */

// @lc code=start

class MyLinkedList {

    public class LinkedNode {
        public var val: Int
        public var next: LinkedNode?

        init(_ val: Int, _ next: LinkedNode? = nil) {
            self.val = val
            self.next = next
        }
    }

    private let dummyHead = LinkedNode(0)
    private var size: Int = 0

    /** Initialize your data structure here. */
    init() {

    }

    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    func get(_ index: Int) -> Int {
        if index > size - 1 || index < 0 {
            return -1
        }
        var cur = dummyHead.next
        var i = index
        while i > 0 {
            cur = cur?.next
            i -= 1
        }
        return cur?.val ?? -1
    }
    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    func addAtHead(_ val: Int) {
        var head = LinkedNode(val)
        head.next = dummyHead.next
        dummyHead.next = head
        size += 1
    }

    /** Append a node of value val to the last element of the linked list. */
    func addAtTail(_ val: Int) {
        var tail = LinkedNode(val)
        var cur: LinkedNode? = dummyHead
        while cur?.next != nil {
            cur = cur?.next
        }
        cur?.next = tail
        size += 1
    }
    //[1, 2, 3, 4, 5, 6]
    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    func addAtIndex(_ index: Int, _ val: Int) {
        if index > size || index < 0 {
            return
        }
        var node = LinkedNode(val)
        var cur: LinkedNode? = dummyHead
        var i = index
        while i > 0 {
            cur = cur?.next
            i -= 1
        }

        node.next = cur?.next
        cur?.next = node

        size += 1
    }

    /** Delete the index-th node in the linked list, if the index is valid. */
    func deleteAtIndex(_ index: Int) {
        if index >= size || index < 0 {
            return
        }
        var cur: LinkedNode? = dummyHead
        var i = index
        while i > 0 {
            cur = cur?.next
            i -= 1
        }
        cur?.next = cur?.next?.next
        size -= 1
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * let obj = MyLinkedList()
 * let ret_1: Int = obj.get(index)
 * obj.addAtHead(val)
 * obj.addAtTail(val)
 * obj.addAtIndex(index, val)
 * obj.deleteAtIndex(index)
 */
// @lc code=end

